package com.ndood.core.social.qq.connect;

import java.nio.charset.Charset;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * SocialAuthenticationFilter默认是不支持qq返回的url参数回调格式的，只支持form，json格式。
 * 所以自定义template使SocialAuthenticationFilter支持text/html，防止认证成功后跳到SocialAuthenticationFilter默认的失败链接/signIn
 */
public class QQOAuth2Template extends OAuth2Template{

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	/**
	 * 构造方法
	 * 查看请求是怎么拼装的OAuth2Template 134
	 * 请求时带上client_id clientSecret
	 */
	public QQOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String accessTokenUrl) {
		super(clientId, clientSecret, authorizeUrl, accessTokenUrl);
		setUseParametersForClientAuthentication(true);
	}

	/**
	 * 覆盖父类方法，构造自定义restTemplate
	 */
	@Override
	protected RestTemplate createRestTemplate() {
		RestTemplate restTemplate= super.createRestTemplate();
		restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
		return restTemplate;
	}

	/**
	 * 解决qq返回的token信息 a&b&c 和springSocial json格式不匹配的问题
	 */
	@Override
	protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
		String responseStr = getRestTemplate().postForObject(accessTokenUrl, parameters, String.class);
		logger.info("获取accessToken的响应："+responseStr);
		
		String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(responseStr, "&");
		String accessToken = StringUtils.substringAfterLast(items[0], "=");
		Long expiresIn = new Long(StringUtils.substringAfterLast(items[1], "="));
		String refreshToken = StringUtils.substringAfterLast(items[2], "=");
		
		return new AccessGrant(accessToken, null, refreshToken, expiresIn);
	}
}
